package com.gemalto.Kryptik;

import bsh.*;
import java.io.*;
import java.util.Hashtable;
import java.util.Enumeration;

public class Beanshell {

//   private static NameSpace nspace = new NameSpace("global namespace");
   private static  Hashtable namespace;


   public static void init(){
	namespace = new Hashtable();
   }



   public static void setVariable(String s, Object o) {
/*		try {
			nspace.setVariable(s,o);
		} catch (EvalError e) {
			System.out.println(e.getMessage());
		}
*/
	namespace.put(s,o);		
   }


   public static NameSpace newNameSpace(){
	NameSpace n = new NameSpace(NameSpace.JAVACODE,"kryptik");
	Enumeration keys = namespace.keys();
	String key ="";

	try {
	  while( keys.hasMoreElements() ){
		key = (String)keys.nextElement();
		n.setVariable(key, namespace.get(key),false);
	  }
	} catch (UtilEvalError e) {
		//Messenger.error(e.getMessage());
		e.printStackTrace();
		System.out.println("key="+key);
	}

	return n;
   }



   public static Interpreter newInterpreter(){
   	Interpreter i = new Interpreter(((Reader) (new StringReader(""))), System.out, System.err, false, newNameSpace());
	try {
		i.eval("import com.gemalto.Kryptik.*;");
		i.eval("import com.gemalto.Kryptik.Algo.*;");
		i.eval("import com.gemalto.Kryptik.Gui.*;");
		i.eval("import com.gemalto.Kryptik.Util.*;");
	} catch (EvalError e){
		Messenger.error(e.getMessage());
		System.err.println("ERROR in BeanShell: Cannot initialize namespace");
	}
	return i;
   }


   public static Interpreter newConsoleInterpreter(ConsoleInterface console){
   	Interpreter i = new Interpreter(console, newNameSpace());
	try {
		i.eval("import com.gemalto.Kryptik.*;");
		i.eval("import com.gemalto.Kryptik.Algo.*;");
		i.eval("import com.gemalto.Kryptik.Gui.*;");
		i.eval("import com.gemalto.Kryptik.Util.*;");
        } catch (EvalError e){
		Messenger.error(e.getMessage());
		System.err.println("ERROR in BeanShell: Cannot initialize namespace");
	}

	return i;
  }

}